//
//  MessageToCell.m
//  HotWord
//
//  Created by Rainbow on 8/11/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MessageToCell.h"
#import "UserManager.h"

#define MESSAGE_TO_CONTENT_LABEL_WIDTH   175
#define MESSAGE_TO_CONTENT_LABEL_MIN_HEIGHT   21
#define MESSAGE_TO_CELL_MIN_HEIGHT   45


@implementation MessageToCell
@synthesize contentLabel;
@synthesize talkBgView;
@synthesize headImageView;
@synthesize timeView;
@synthesize timeLabel;
@synthesize currentMessage = _currentMessage;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setMessage:(Message *)message
{
    self.currentMessage = message;
    CGSize labelSize = [MessageToCell getContentHeightByContent:message.content];
    self.contentLabel.height = labelSize.height;
    self.contentLabel.width = labelSize.width;
    self.talkBgView.width = labelSize.width + 50;
    self.contentLabel.right = 246;
    self.talkBgView.right = 279;
    self.talkBgView.height = self.contentLabel.height + 24;
    self.failedBtn.right = self.contentLabel.left - 20;
    self.timeView.layer.cornerRadius = 6;  
    self.timeLabel.text = [UtilHelper getDateString:[message.timestamp longLongValue] withFormat:@"yyyy-MM-dd hh:mm"];
    self.contentLabel.text = message.content;
    [self.headImageView loadImage:[UserManager sharedManager].currentUser.avater];
    if ([message.isSentFailed boolValue]) {
        self.failedBtn.hidden = NO;
    }
    else{
        self.failedBtn.hidden = YES;
    }
}


+ (CGSize)getContentHeightByContent:(NSString *)content
{
    CGSize labelSize = [content sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(MESSAGE_TO_CONTENT_LABEL_WIDTH, 1000) lineBreakMode:UILineBreakModeWordWrap];
    if (labelSize.width < 45) {
        labelSize.width = 45;
    }
    if (labelSize.height < MESSAGE_TO_CONTENT_LABEL_MIN_HEIGHT) {
        return CGSizeMake(labelSize.width, MESSAGE_TO_CONTENT_LABEL_MIN_HEIGHT);
    }
    else {
        return labelSize;
    }
}

+ (CGFloat)getCellHeightByContent:(NSString *)content
{
    return MESSAGE_TO_CELL_MIN_HEIGHT + [MessageToCell getContentHeightByContent:content].height - MESSAGE_TO_CONTENT_LABEL_MIN_HEIGHT;
}

- (IBAction)tapOnResendBtn:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(resendMessage:)]) {
        [self.delegate resendMessage:_currentMessage];
    }
}

- (void)dealloc {
    [_currentMessage release];
    [contentLabel release];
    [headImageView release];
    [talkBgView release];
    [timeView release];
    [timeLabel release];
    [_failedBtn release];
    [super dealloc];
}
@end
